<?php
class order extends CI_Controller {

	const SEND_SMS = true;
	const TELEPHONE = "15811027275";
	//const TELEPHONE = "13426202522";
	//const TELEPHONE = "13811789363";
	//const SEND_SMS = false;


	function index()
	{
		/*
		 echo "Welcome to orderdetail\n";
		 $this->load->model('orderdetail_model');
		 //$data['labelArray'] = $this->label->get_last_ten_entries();
		 $data['title'] = "order Detail Page";
		 $this->load->view('order/checkout', $data);
		 */
	}

	/**
	 * 用户checkout页，列出cart信息，和已有的Address
	 * Enter description here ...
	 */
	function checkout()
	{
		$data['title'] = "送饭啦结账";
		$this->load->model('food_model');
		
		$cartFoodArray = array();
		
		//取当前用户地址
		$userId = $this->session->userdata('user_id');
		//未登陆用户设置user_id=0
		if($userId==null)
		{
			//TODO 为了测试设置成1，要改回0
			$userId = 0;
		}
		
		//取user地址信息
		if($userId!=0)
		{
			$this->load->model('deliveraddress_model');
			$deliverAddressArray = $this->deliveraddress_model->getAddressByUserid($userId);
		}else {
			$deliverAddressArray = array();
		}
		//print_r($deliverAddressArray);
		
		//取当前的购物车信息
		$this->load->model('cart_model');
		$cart = $this->cart_model->getCartInfo();
		
		//print_r($cart);
		//设置cart和deliveraddress， 跳转到view
	
		$data['userId'] = $userId;
		$data['cart'] = $cart;
		$data['deliverAddressArray'] = $deliverAddressArray;
		$this->load->view('order/checkout', $data);
	}

	/**
	 * 
	 * 验证表单:基本信息，包括address的选择。
	 * 		当选择已有address时不需要验证表单
	 * 验证food信息，包括：非空，属于同一饭店，从数据库核实价格
	 * 保存订单信息，userid取自session。orderdetail和orderitem都要保存
	 */
	function submitOrder()
	{
		//print_r($_POST);
		//验证送饭信息表单
		if(isset($_POST['foodCartArray'])==false)
		{
			echo "购物车为空，不能下单";
			return;
		}
		$this->load->library('form_validation');
		//form验证，为了实现Re-populating，需要验证，trim就可以了
		$this->form_validation->set_rules('radio_address', '地址', 'trim');
		$this->form_validation->set_rules('user_sex', '性别', 'trim');
		$this->form_validation->set_rules('deliverMemo', '备注信息', 'trim');
		
		$this->form_validation->set_message('required', '请正确填写 %s');
		
		//如果选择新地址，那么要验证
		if($_POST['radio_address'] =="new_address"){
			$this->form_validation->set_rules('deliverAddress', '地址', 'required');
			$this->form_validation->set_rules('deliverName', '姓名', 'required');
			$this->form_validation->set_rules('deliverPhone', '电话', 'required');			
		}
				
		$this->form_validation->set_rules('deliverTime', '送餐时间', 'required');
		
		//要保证orderitem的quantity大于0
		if ($this->form_validation->run() == FALSE)
		{
			$this->checkout();
			return;
			//redirect("order/order/checkout",'checkout');
			//$this->load->view('order/checkout', $data);
		}
		else
		{	
			
			$restaurantCart = $_POST['foodCartArray'];
			//得到foodid=>quantity对
			$orderitemArray = array();
			foreach($restaurantCart as $foodID => $foodCart)
			{				
				$orderitem['foodID'] = $foodCart['foodID'];
				$orderitem['quantity'] = $foodCart['quantity'];
				$orderitemArray[] = $orderitem;
			}
			
			$this->load->model('food_model');
			$totalPrice = 0;
			
			//填充价格
			//为了保证安全，价格要从数据库获取，店铺id要通过数据库检查一致，不能相信browser发过来的数据
			$restaurantIDArray = array();
			
			foreach ($orderitemArray as &$oneOrderitem)
			{
				$foodInfo = $this->food_model->load($oneOrderitem['foodID']);
				//restaurantID留着一会检查一致性
				$restaurantIDArray[] = $foodInfo['restaurantId'];
				if(empty($foodInfo))
				{
					echo "foodid: {$oneOrderitem['foodID']}不存在。不能下单。";
					return;
				}
				$oneOrderitem['subtotal'] = $foodInfo['unitPrice']*$oneOrderitem['quantity'];
				$totalPrice += $oneOrderitem['subtotal'];
			}
			
			//需要检查food属于同一家restaurant			
			$restaurantId = $this->checkRestaurantID($restaurantIDArray);			
			if($restaurantId == -1)
			{
				echo "food 不属于同一家 restaurant 不能下单";
				return;
			}
			
			$userId = $this->session->userdata('user_id');
			//TODO 确保登陆非登陆都可用。userid=0表示没有登陆的用户
			if($userId == null) $userId = 0;
			
			
			$orderDetail['userId'] = $userId;
			$orderDetail['restaurantId'] = $restaurantId;		
			$orderDetail['totalPrice'] = $totalPrice;
			$orderDetail['deliverTime'] = $_POST['deliverTime'];
			$orderDetail['deliverAddressId'] = null;
			$orderDetail['memo'] = isset($_POST['deliverMemo'])?$_POST['deliverMemo']:null;
			//TODO need to solve
			$orderDetail['serialNumber'] = date("ymdHis").sprintf('%03d',rand(0,999));
			
			if($_POST['radio_address'] =="new_address")
			{
				$orderDetail['deliverName'] = $_POST['deliverName'];
				$orderDetail['deliverAddress'] = $_POST['deliverAddress'];
				$orderDetail['deliverPhone'] = $_POST['deliverPhone'];
			}
			else
			{
				//TODO 需要检查cheat
				$oldAddressID = $_POST['radio_address'];
				$oldAddressArray = $_POST['old_address'];
				$selectAddress = $oldAddressArray[$oldAddressID];
				$orderDetail['deliverName'] = $selectAddress['deliverName'];
				$orderDetail['deliverAddress'] = $selectAddress['deliverAddress'];
				$orderDetail['deliverPhone'] = $selectAddress['deliverPhone'];
				
			}
			
			//保存orderDetail			
			$this->load->model('orderdetail_model');
			$this->orderdetail_model->insert_orderdetail($orderDetail);
			$orderId = $this->db->insert_id();
			
			//echo "<br> 订单信息<br> ";
			//print_r($orderDetail);
			//echo "<br>";			
			//print_r($orderitemArray);
			
			//填充orderid,保存orderitem
			$this->load->model('orderitem_model');
			foreach ($orderitemArray as &$oneOrderitem)
			{
				$oneOrderitem['orderID'] = $orderId;				
				$this->orderitem_model->insert_orderitem($oneOrderitem);
			}
			
			$data['title'] = "下单成功";
			$data['orderDetail'] = $orderDetail;
			$data['orderitemArray'] = $orderitemArray;
			//clear session cart
			$this->session->set_userdata('cart', array());
			$this->load->view('order/orderSuccess', $data);
			if(order::SEND_SMS)$this->sendNoticeToRestaurant($orderDetail, $orderitemArray);
		}

	}
	function constructSMS($orderDetail,$orderitemArray){
		//"中科院F座,王强,15811027275; 1*宫保鸡丁盖饭(11),1*番茄牛腩盖饭(19), 1豆浆(2); 共32元"
		$address = $orderDetail['deliverAddress'].","
		.$orderDetail['deliverName'].",".
		$orderDetail['deliverPhone'];
		
		$foodInfo = "";
		$this->load->model('food_model');
		foreach ($orderitemArray as &$oneOrderitem)
		{
			$foodID = $oneOrderitem['foodID'];				
			$food = $this->food_model->load($foodID);
			$foodInfo .=$oneOrderitem['quantity']."*".$food['name']. "-" .$food['unitPrice']. ",";
		}
		$foodInfo = substr($foodInfo,0,strlen($foodInfo)-1);
		$price = "共".$orderDetail['totalPrice']."元";
		$memo = $orderDetail['memo'];
		
		$message = $address.";".$foodInfo. ";".$price.";".$memo ;
		if(strlen($message) >=130){
			//TODO 是否限制短信长度
			//$message = substr($message,0,129);
		}		
		return $message;
	}
	function sendNoticeToRestaurant($orderDetail,$orderitemArray){
		$message = $this->constructSMS($orderDetail,$orderitemArray);
		//echo $message;
		
		$telephone = order::TELEPHONE;
		$url = base_url()."order/sendSMSInternal";
		$params['message'] = $message;
		$params['telephone'] = $telephone;
		$this->curl_post_async($url,$params);
		$url = base_url()."order/sendEmailInternal";
		$this->curl_post_async($url,$params);
	}
	
	function sendSMSInternal(){		
		log_message('error', 'sendSMSInternal function 11');
		//$message = "test message 1";
		echo $telephone = $_POST['telephone'];
		echo $message = $_POST['message'];
		$this->sendsmsByDONGSHIFANG($telephone, $message);
		//$this->sendsmsBySMSGATE($telephone, $message);
		//$this->sendsmsBySMS($telephone, $message);
		//$this->sendsmsByDONGSHIFANG($telephone, $message);
		echo $message;
	}
	function sendEmailInternal(){
		log_message('error', 'sendEmailInternal function 11');
		echo $message = $_POST['message'];
		$this->sendOrderEmail($message);
	}
	function sendOrderEmail($message){
		$this->load->library('email');
		$this->email->from('email_songfanla@163.com', 'Songfanla Email');
		$this->email->to( array('email_songfanla@163.com','email.songfanla@gmail.com','cawood@qq.com') ); 
		$this->email->subject(substr($message, 0,110));
		$this->email->message($message);	
		
		$this->email->send();
		log_message('error', $this->email->print_debugger());
	}
	
	function sendTest(){
		//log_message('error', 'sendTest function');
		//TODO change to base url.
		$url = base_url()."order/sendSMSInternal";
		$params['message'] = "test new message";
		$params['telephone'] = "15811027275";
		//$this->curl_post_async($url,$params);
		echo "Success";
		echo base_url()."order/sendSMSInternal";
		print_r($_SERVER);
	}
	
	function curl_post_async($url, $params)
	{
	    foreach ($params as $key => &$val) {
	      if (is_array($val)) $val = implode(',', $val);
	        $post_params[] = $key.'='.urlencode($val);
	    }
	    $post_string = implode('&', $post_params);
	
	    $parts=parse_url($url);
	
	    $fp = fsockopen($parts['host'],
	        isset($parts['port'])?$parts['port']:80,
	        $errno, $errstr, 30);
	
	    $out = "POST ".$parts['path']." HTTP/1.1\r\n";
	    $out.= "Host: ".$parts['host']."\r\n";
	    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
	    $out.= "Content-Length: ".strlen($post_string)."\r\n";
	    $out.= "Connection: Close\r\n\r\n";
	    if (isset($post_string)) $out.= $post_string;
		log_message('error', $out);
	
	    fwrite($fp, $out);
	    fclose($fp);
	}
	function sendsmsBySMSGATE($telephone,$message){
		$myusername = "wlzmwq";
		$mypassword = "cangjingkong";
		
		$url="http://www.smsgate.cn/utf.asp";
		//$params = "lng=1&usr=wlzmwq&pwd=cangjingkong&tel=15811027275&msg=北京市中关村清华大学建筑系5号楼,罗宇,15234027222;1*全翅套餐%20-10,1*泰式鸡块套餐-11,;共21元";
		$params = "lng=0&usr=".$myusername."&pwd=".$mypassword."&tel=".$telephone."&msg=".$message;
		//$url="http://www.smsgate.cn/utf.asp?usr=".$myusername."&pwd=".$mypassword."&tel=".$telephone."&msg=".$message;
		//$url = "http://www.google.com";
		//$html = file_get_contents($url); 
		$html = $this->fetch_page("smsgate",$url,$params); 
		//echo $html;
	}
	
	
	function sendsmsBySMS($telephone,$message){
		$url = "http://www.smsadmin.cn/smsmarketing/wwwroot/api/get_send";
		//?uid=ID&pwd=密码&mobile=手机号&msg=短信内容&dtime=时间(时间为空为立即发送,格式:2007-12-01
		$id= "100220";
		$pwd="123456";		
		$params = "uid=".$id."&pwd=".$pwd."&mobile=".$telephone."&msg=".$message;
		echo $url."?".$params;
		$html = $this->fetch_page("sms",$url,$params); 
	}
	
	function sendsmsByDONGSHIFANG($telephone,$message){
		//echo strlen($message);
		//$message= substr($message,0,70);
		//$url = "http://api.xhsms.com/gb2312/web_api/"; //GBK
		$url = "http://api.xhsms.com/utf8/web_api/";//utf-8
		//?uid=ID&pwd=密码&mobile=手机号&msg=短信内容&dtime=时间(时间为空为立即发送,格式:2007-12-01
		$uid= "songfl";
		$pwd_md5="d5b6c6d90c803eb0a9ab4c88eef5c08e";//cangjingkong		
		$params = "x_eid=0&x_uid=".$uid."&x_pwd_md5=".$pwd_md5."&x_ac=12&x_gate_id=300&x_target_no=".$telephone."&x_memo=".$message;
		//echo $url."?".$params;
		$html = $this->fetch_page("sms",$url,$params); 
		//echo $html;
		if($html<=0)echo $html;
		return $html;
	}
	
	function fetch_page($site,$url,$params=false) 
	{ 
	    $ch = curl_init(); 
	    $cookieFile = $site . '_cookiejar.txt'; 
	    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); 
	    curl_setopt($ch, CURLOPT_COOKIEFILE,$cookieFile); 
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
	    //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,   FALSE); 
	    curl_setopt($ch, CURLOPT_HTTPGET, true); 
	    curl_setopt($ch, CURLOPT_TIMEOUT, 4); 
	    if($params)
	    {
	        curl_setopt($ch, CURLOPT_POSTFIELDS, $params); 
	    }
	    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'); 
	    curl_setopt($ch, CURLOPT_URL,$url); 
	
	    $result = curl_exec($ch); 
	    //file_put_contents('jobs.html',$result); 
	    return $result; 
	} 
	
	function checkRestaurantID($restaurantIDArray)
	{
		$tempRestaurantID = -1;
		foreach ($restaurantIDArray as $oneRestaurantID)
		{
			if($tempRestaurantID == -1)
			{
				$tempRestaurantID = $oneRestaurantID;
			}
			
			if($oneRestaurantID != $tempRestaurantID)
			{
				echo "Error food 不属于同一家 restaurant";
				return -1;
			}
		}
		return $tempRestaurantID;
		
	}
}